package adv8.server1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author oldliu
 * @since 1.0
 */
public class AdvanceChatServer {
    public static void main(String[] args) {
        ServerSocket st = null;
        //线程池
        ExecutorService es = Executors.newFixedThreadPool(20);
        try {
            st = new ServerSocket(8888);
            System.out.println("聊天服务器启动。。。");
            while (true) {
                final Socket s = st.accept();
                //submit
                es.execute(new ChatThread(s));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

class ChatThread implements Runnable {
    private Socket s;

    public ChatThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        System.out.println(s + "连接上服务器了，准备聊天");
        try {
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            //聊天
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            PrintWriter pw = new PrintWriter(out, true);//true表示自动刷新
            String line = null;

            while ((line = br.readLine()) != null) {
                System.out.println(s + "说:" + line);
                pw.println("你说的话:" + line + "，朕知道了" + new Date());
                //pw.flush();
                if ("byebye".equals(line)) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                s.close();
                System.out.println(s + "关闭连接");
            } catch (Exception e) {

            }
        }
    }
}
